// 234. 回文链表

// 请判断一个链表是否为回文链表。

// 示例 1:
// 输入: 1->2
// 输出: false

// 示例 2:
// 输入: 1->2->2->1
// 输出: true

// 进阶：
// 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题？

const { ListNode } = require("./common.js");
const { reverseList } = require("./206.js");

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
  let slow = head;
  let fast = head;
  while (fast.next && fast.next.next) {
    slow = slow.next;
    fast = fast.next.next;
  }
  let h = slow;
  slow = reverseList(slow.next);
  let temp = head;
  let s = slow;
  while (s) {
    if (s.val != temp.val) {
      return false;
    }
    s = s.next;
    temp = temp.next;
  }
  h.next = reverseList(slow);
  return true;
};

const node = new ListNode(1, new ListNode(2, null));
console.log(node.toString());
console.log(isPalindrome(node));
console.log(node.toString());
const node2 = new ListNode(
  1,
  new ListNode(2, new ListNode(2, new ListNode(1, null)))
);
console.log(node2.toString());
console.log(isPalindrome(node2));
console.log(node2.toString());
